package middlewares

import (
	"github.com/gin-gonic/gin"
	"net"
	"net/http"
	"strings"
)

func Request() gin.HandlerFunc {
	return func(c *gin.Context) {
		manufacturer := c.Request.Header.Get("manufacturer")      //制造商,例：HONOR
		userAgent := c.Request.Header.Get("user_agent")           //UA
		sdkVersion := c.Request.Header.Get("sdk_version")         //sdk版本号,如1.0.0
		devicePlatform := c.Request.Header.Get("device_platform") //平台，例： Unknow Android 、iOS
		deviceType := c.Request.Header.Get("device_type")         //设备类型, 如：V2279A
		osVersion := c.Request.Header.Get("os_version")           //系统版本： 例：13
		channel := c.Request.Header.Get("channel")                //渠道：服务商户名称
		deviceID := c.Request.Header.Get("device_id")             //设备ID（唯一标识）
		osName := c.Request.Header.Get("os_name")                 //系统名称,Android 13
		c.Set("manufacturer", manufacturer)
		c.Set("userAgent", userAgent)
		c.Set("sdkVersion", sdkVersion)
		c.Set("devicePlatform", devicePlatform)
		c.Set("deviceType", deviceType)
		c.Set("osVersion", osVersion)
		c.Set("channel", channel)
		c.Set("deviceID", deviceID)
		c.Set("osName", osName)
		c.Set("clientIp", ClientIP(c.Request))
		c.Next()
	}
}

// ClientIP 尽最大努力实现获取客户端 IP 的算法。
// 解析 X-Real-IP 和 X-Forwarded-For 以便于反向代理（nginx 或 haproxy）可以正常工作。
func ClientIP(r *http.Request) string {
	xForwardedFor := r.Header.Get("X-Forwarded-For")
	ip := strings.TrimSpace(strings.Split(xForwardedFor, ",")[0])
	if ip != "" {
		return ip
	}
	ip = strings.TrimSpace(r.Header.Get("X-Real-Ip"))
	if ip != "" {
		return ip
	}
	if ip, _, err := net.SplitHostPort(strings.TrimSpace(r.RemoteAddr)); err == nil {
		return ip
	}
	return ""
}
